package com.fzdy.product.controller;

import com.alibaba.fastjson.JSONObject;
import com.fzdy.product.config.ShiroConfig;
import com.fzdy.product.dao.UserDao;
import com.fzdy.product.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {
    @Autowired
    private UserDao userDao;

    @Autowired
    private ShiroConfig shiroConfig;

    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public JSONObject notLogin() {
        JSONObject resobj = new JSONObject();
        resobj.put("statusCode", 300);
        resobj.put("message", "您尚未登陆！");
        return resobj;
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public JSONObject notRole() {
        JSONObject resobj = new JSONObject();
        resobj.put("statusCode", 300);
        resobj.put("message", "您没有权限！");
        return resobj;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JSONObject logout() {
        Subject subject = SecurityUtils.getSubject();
        //注销
        subject.logout();
        JSONObject resobj = new JSONObject();
        resobj.put("statusCode", 200);
        resobj.put("message", "成功注销！");
        return resobj;
    }

    /**
     * 登陆
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONObject login(@RequestBody User user, HttpServletRequest request) {
        System.out.println(request.getSession().getId());
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
        ShiroFilterFactoryBean bean = shiroConfig.getShiroFilterFactoryBean();
        // 执行认证登陆
        subject.login(token);
        //根据权限，指定返回数据

        JSONObject resobj = new JSONObject();
        resobj.put("statusCode", 200);
        resobj.put("message", "登录成功！");

        return resobj;
    }
}

